const { sequelize, DataTypes } = require('../config/database');
const bcrypt = require('bcryptjs');

const User = sequelize.define('User', {
  id: {
    type: DataTypes.INTEGER,
    primaryKey: true,
    autoIncrement: true
  },

  // WeChat Mini Program specific fields
  openId: {
    type: DataTypes.STRING,
    unique: true,
    allowNull: true
  },

  unionId: {
    type: DataTypes.STRING,
    unique: true,
    allowNull: true
  },

  // Basic user information
  nickname: {
    type: DataTypes.STRING(50),
    allowNull: false,
    validate: {
      notEmpty: true,
      len: [1, 50]
    }
  },

  avatarUrl: {
    type: DataTypes.STRING,
    defaultValue: 'https://picsum.photos/200/200?random=1'
  },

  gender: {
    type: DataTypes.TINYINT,
    defaultValue: 0,
    validate: {
      isIn: [[0, 1, 2]] // 0: unknown, 1: male, 2: female
    }
  },

  bio: {
    type: DataTypes.STRING(200),
    defaultValue: '',
    validate: {
      len: [0, 200]
    }
  },

  // Contact information
  phone: {
    type: DataTypes.STRING,
    unique: true,
    allowNull: true,
    validate: {
      is: /^1[3-9]\d{9}$/
    }
  },

  email: {
    type: DataTypes.STRING,
    unique: true,
    allowNull: true,
    validate: {
      isEmail: true
    }
  },

  // Location information (JSON)
  location: {
    type: DataTypes.JSON
  },

  // User preferences (JSON)
  preferences: {
    type: DataTypes.JSON
  },

  // Activity statistics (JSON)
  statistics: {
    type: DataTypes.JSON
  },

  // Account status
  status: {
    type: DataTypes.ENUM('active', 'inactive', 'suspended', 'deleted'),
    defaultValue: 'active'
  },

  // Verification status
  isVerified: {
    type: DataTypes.BOOLEAN,
    defaultValue: false
  },

  // Last login information
  lastLoginAt: {
    type: DataTypes.DATE
  },

  lastLoginIP: {
    type: DataTypes.STRING
  },

  // WeChat session key (for decryption)
  sessionKey: {
    type: DataTypes.STRING
  },

  // JWT token for API authentication
  jwtToken: {
    type: DataTypes.STRING
  },
  password: {
    type: DataTypes.STRING,
    allowNull: true,
    set(value) {
      if (value) {
        const salt = bcrypt.genSaltSync(10);
        this.setDataValue('password', bcrypt.hashSync(value, salt));
      }
    }
  }

}, {
  tableName: 'parkpart_users',  // 修改表名
  timestamps: true,
  paranoid: true,
  indexes: [
    { unique: true, fields: ['openId'] },
    { unique: true, fields: ['unionId'] },
    { fields: ['nickname'] },
    { fields: ['status'] },
    { fields: ['createdAt'] }
  ]
});

// 关联表定义
User.associate = (models) => {
  // 自关联：关注者
  User.belongsToMany(User, {
    through: 'parkpart_user_followers',  // 修改关联表名
    as: 'followers',
    foreignKey: 'followingId',
    otherKey: 'followerId'
  });

  // 自关联：关注的人
  User.belongsToMany(User, {
    through: 'parkpart_user_followers',  // 修改关联表名
    as: 'following',
    foreignKey: 'followerId',
    otherKey: 'followingId'
  });

  // 自关联：好友
  User.belongsToMany(User, {
    through: 'parkpart_user_friends',  // 修改关联表名
    as: 'friends',
    foreignKey: 'userId',
    otherKey: 'friendId'
  });

  // 用户创建的活动
  User.hasMany(models.Activity, {
    foreignKey: 'creatorId',
    as: 'createdActivities'
  });

  // 用户参与的活动
  User.belongsToMany(models.Activity, {
    through: 'parkpart_activity_participants',  // 修改关联表名
    as: 'participatedActivities',
    foreignKey: 'userId',
    otherKey: 'activityId'
  });

  // 用户点赞的活动
  User.belongsToMany(models.Activity, {
    through: 'parkpart_activity_likes',  // 修改关联表名
    as: 'likedActivities',
    foreignKey: 'userId',
    otherKey: 'activityId'
  });

  // 用户评论
  User.hasMany(models.Comment, {
    foreignKey: 'userId',
    as: 'comments'
  });
};

// 实例方法
User.prototype.getPublicProfile = function () {
  return {
    id: this.id,
    nickname: this.nickname,
    avatarUrl: this.avatarUrl,
    gender: this.gender,
    bio: this.bio,
    location: this.location,
    statistics: this.statistics,
    isVerified: this.isVerified,
    createdAt: this.createdAt,
    updatedAt: this.updatedAt
  };
};

User.prototype.toJSON = function () {
  const values = Object.assign({}, this.get());
  delete values.sessionKey;
  delete values.jwtToken;
  delete values.password;
  return values;
};

// 钩子函数
User.beforeCreate(async (user) => {
  // 设置默认值
  if (!user.location) user.location = {};
  if (!user.preferences) user.preferences = {
    activityTypes: [],
    notificationEnabled: true,
    locationSharingEnabled: true
  };
  if (!user.statistics) user.statistics = {
    activitiesCreated: 0,
    activitiesJoined: 0,
    totalLikesReceived: 0,
    totalCommentsReceived: 0,
    rating: 0,
    ratingCount: 0
  };
});

User.beforeUpdate(async (user) => {
  // 确保JSON字段有值
  if (!user.location) user.location = {};
  if (!user.preferences) user.preferences = {
    activityTypes: [],
    notificationEnabled: true,
    locationSharingEnabled: true
  };
  if (!user.statistics) user.statistics = {
    activitiesCreated: 0,
    activitiesJoined: 0,
    totalLikesReceived: 0,
    totalCommentsReceived: 0,
    rating: 0,
    ratingCount: 0
  };
});

module.exports = User;